package com.filetransfer.view.Components.render;
import com.filetransfer.utils.SvgIconUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
public class TextWithCopyButton extends JPanel {
    private final JButton copyButton;
    public TextWithCopyButton(String text) {
        setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        setOpaque(false);
        // 初始化按钮
        copyButton = new JButton(text, SvgIconUtil.createSvgIcon("icons/content_copy.svg", 20, 20));
        copyButton.setFocusPainted(false);
        copyButton.setPreferredSize(new Dimension(100, 20));
        copyButton.setHorizontalTextPosition(SwingConstants.LEFT);
        copyButton.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
        copyButton.setToolTipText("复制到剪切板: " + text);
        // 使用动态获取文本的方式
        copyButton.addActionListener(e -> {
            String currentText = copyButton.getText(); // 动态获取按钮的文本
            try {
                StringSelection stringSelection = new StringSelection(currentText);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                JOptionPane.showMessageDialog(this, "已复制到剪切板: " + currentText, "复制成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "复制失败，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        add(copyButton);
    }
    public void setText(String text) {
        copyButton.setText(text);
        copyButton.setToolTipText("复制到剪切板: " + text);
    }
}
